package org.ezplatform.office.forum.util.forumpostsend;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.ezplatform.cloud.common.log.LogService;
import org.ezplatform.mobile.util.message.service.MobileMessageService;
import org.ezplatform.office.forum.entity.ForumPost;
import org.ezplatform.util.GlobalConstant;
import org.ezplatform.util.JsonUtils;
import org.ezplatform.util.RestClient;
import org.ezplatform.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class ForumPostSendUtils {

	
	/**
     * 论坛模块 码
     */
    public static final String MODULE = "stdForum";


    /**
     * 论坛消息 id（未修改）
     */
    public static final String MODULEID = "4f4f27c7778711e9847400505683e8cd";


    /**
     * office铃铛推送路径
     */
    public static final String URL = "modules/forum/html/forum_post/view_post.html";


    /**
     * 微信推送
     */
    public static final String WX = "wxWork";

    /**
     * 钉钉
     */
    public static final String DING = "ding";

    /**
     * evo门户
     */
    public static final String EVO = "evoPorta";

    private RestClient restClient = new RestClient(false);
    
    @Autowired
	private static LogService logService;

    /**
     * 所有的都推送
     */
    public static final String ALLSENDPATH = "wxWork,ding,evoPorta";
	
    
    /**
	 * 获取后台设置参数
	 * @param corpId
	 * @param token
	 * return (wxWork,ding,evoPortal)
	 */
	public static String getSysImType(String corpId, String token) {
		RestClient restClient = new RestClient(true);
		Map<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("corpId", corpId);
		paramMap.put("mark", "sysImType");
		String jsonStr = restClient.get("/system/config/getConfigValue", token, paramMap);
		Map<String, Object> result = JsonUtils.readValue(jsonStr);
		if(MapUtils.isNotEmpty(result)) {
			if("success".equals(result.get("type"))){
				return String.valueOf(result.get("data"));
			}
		}
		return "";
	}
	
	/**
     * 信息发送方法
     * @param mobileMessageService 发送方法service
     * @param baseCorpId    平台单位id
     * @param userId    平台用户id(非必填项)
     * @param deptId    平台组织id(非必填项)
     * @param map       其他参数<br>
     *                  name        姓名  <br>
     *                  title       论坛标题<br>
     *                  url         项目路径<br>
     *                  isEdit      是否可以编辑<br>
     *                  cateName    论坛风雷<br>
     *                  startTime   论坛开始时间(全天论坛开始结束时间显示相同日期)<br>
     *                  endTime     论坛结束时间<br>
     *                  calendarId  论坛id<br>
     *                  repeat      是否是重复论坛<br>
     *                  isJob       是否是定时任务的提醒 (1是；0不是)<br>
     *                  remindStyle 推送方式(mail 邮件，mobile 移动端)
     *
     *                  sendPath    推送途径，钉钉，微信，门户，直接将后台的数据放进去<br>
     *
     */
	@Async
    public static void sendMsg(MobileMessageService mobileMessageService, HttpServletRequest request, String baseCorpId, String userId, String deptId, Map<String,String> map) {
        String webUrl = "";
        webUrl = GlobalConstant.getFlexOfficePageUrl(request);
        String context = convertContextPath(webUrl);
        String dingFrontUrl = GlobalConstant.getConfig("app.mobile.ding.front.url");
        String menhuFronUrl = GlobalConstant.getConfig("app.mobile.menhu.front.url");

        //接收消息消息类型
        Map<String,String> msgTypeMap = new HashMap<>();

        //接收消息消息内容
        Map<String,Object> messageMap = new HashMap<>();
        StringBuffer oaMessage = new StringBuffer();
        String messageUrl = "/mobile/modules/forum/dist/index.html?contextPath="+context
               + "&dd_nav_bgcolor=FF5E97F6#/post/view/"
                + map.get("id") + "/"+map.get("checkStatus")+"/"+map.get("isModerator")+"/"+map.get("author")+"/"+map.get("isAuthor")+"/"+(map.get("checkStatus").equals("1")?"myCheck":"all");

        String pcurl = "/web/dist/modules/forum/html/forum_post/view_post.html?window&vieweditid="+map.get("id")+"&navigationcollect=5"+"&checkstatus="+map.get("checkStatus");
        
        String pcWebUrl = GlobalConstant.getConfig("app.mobile.cocall.front.url");

        //钉钉推送
        if (map.get("sendPath").indexOf(DING) >= 0) {
        	 //审核中推送 钉钉端 checkStatus：1
        	 //审核不通过推送 钉钉端 checkStatus：3
            if (StringUtils.equals("1", map.get("checkStatus"))) {
            	oaMessage.append("{\"message_url\":\"" + messageUrl + "\",\"pcurl\":\""  + pcurl  + "\","
                        + "\"head\": {\"bgcolor\":\"4D98C9\",\"text\": \"论坛提醒\"}," + "\"body\": {\"title\":\""
                        + "新发表的帖子等待您的审核，请尽快完成\"," + "\"form\": [{\"key\":\"帖子标题:\",\"value\":\""
                        + map.get("title") + "\"},{\"key\": \"发帖人:\",\"value\": \""
                        + map.get("userName") + "\"}]" + "}}");
            } else if (StringUtils.equals("3", map.get("checkStatus"))){
                oaMessage.append("{\"message_url\":\"" + messageUrl + "\",\"pcurl\":\""  + pcurl  + "\","
                        + "\"head\": {\"bgcolor\":\"4D98C9\",\"text\": \"论坛提醒\"}," + "\"body\": {\"title\":\""
                        + "您发表的帖子审核未通过\"," + "\"form\": [{\"key\":\"帖子标题:\",\"value\":\""
                        + map.get("title") + "\"},{\"key\": \"驳回理由:\",\"value\": \""
                        + map.get("rejection") + "\"}]" + "}}");
            }
            	Map<String, Object> messageContent = new HashMap<String, Object>();
                msgTypeMap.put("DING", "oa");
                messageContent.put("oa", JsonUtils.readValue(oaMessage.toString()));
                messageMap.put("DING",messageContent);
        }


        
        if (map.get("sendPath").indexOf(WX) >= 0) {
            String wxMessage = "";
            String domain = GlobalConstant.getConfig("app.mobile.weixin.front.url");
            //审核中推送 微信 checkStatus：1
       	 	//审核不通过推送 微信 checkStatus：3
            String title = "";
            String titledescription = "新发表的帖子等待您的审核，请尽快完成";
            if (StringUtils.equals("1", map.get("checkStatus"))) {
            	title = "帖子标题:"+ map.get("title")+" <br />发帖人:"+map.get("userName");
            		wxMessage = "{\"articles\" : [{" +
                            "\"title\" : \""+titledescription+"\"," +
                            "\"pcurl\":\""  + pcurl  + "\","+
                            "\"description\" : \"" + title + "\"," +
                            "\"url\" : \""  + messageUrl + "\"" +
                            "}]}";
            }else if (StringUtils.equals("3", map.get("checkStatus"))){
            	title = "帖子标题:"+ map.get("title")+" <br />驳回理由:"+map.get("rejection");
                wxMessage = "{\"articles\" : [{" +
                        "\"title\" : \"您发表的帖子审核未通过！\"," +
                        "\"pcurl\":\""  + pcurl  + "\","+
                        "\"description\" : \"" + title + "\"," +
                        "\"url\" : \""  + messageUrl + "\"" +
                        "}]}";
            }
	            Map<String, Object> wxMessageContent = new HashMap<String, Object>();
	            msgTypeMap.put("WX", "news");
	            wxMessageContent.put("news", JsonUtils.readValue(wxMessage));
	            messageMap.put("WX", wxMessageContent);
        }

       
        //evo
        if (map.get("sendPath").indexOf(EVO) >= 0) {
        	 //门户信息
            String mhMessage = "";
            //审核中推送 门户 checkStatus：1
       	 	//审核不通过推送 门户 checkStatus：3
            String title = "";
            if (StringUtils.equals("1", map.get("checkStatus"))) {
            	title = "帖子标题:"+ map.get("title")+"  发帖人:"+map.get("userName");
            		 mhMessage = "{\"articles\" : [{" +
                             "\"title\" : \"新发表的帖子等待您的审核，请尽快完成\"," +
                             "\"pcurl\":\""  + pcurl  + "\","+
                             "\"description\" : \"" + title + "\"," +
                             "\"appUrl\" : \""  + messageUrl + "\"" +
                             "}]}";
            }else if (StringUtils.equals("3", map.get("checkStatus"))){
            	title = "帖子标题:"+ map.get("title")+"   驳回理由:"+map.get("rejection");
                mhMessage = "{\"articles\" : [{" +
                        "\"title\" : \"您发表的帖子审核未通过\"," +
                        "\"pcurl\":\""  + pcurl  + "\","+
                        "\"description\" : \"" + title + "\"," +
                        "\"appUrl\" : \""  + messageUrl + "\"" +
                        "}]}";
            }
	            Map<String, Object> mhMessageContent = new HashMap<String, Object>();
	            msgTypeMap.put("MH", "news");
	            mhMessageContent.put("news", JsonUtils.readValue(mhMessage));
	            messageMap.put("MH", mhMessageContent);
        }
        
        //CoCall
        if (map.get("sendPath").indexOf("CoCall") >= 0) {
        	String cocallUrl = GlobalConstant.getConfig("app.mobile.cocall.front.url");
        	 //COCALL信息
            String mhMessage = "";
            //审核中推送 门户 checkStatus：1
       	 	//审核不通过推送 门户 checkStatus：3
            String title = "";
            if (StringUtils.equals("1", map.get("checkStatus"))) {
            	title = "帖子标题:"+ map.get("title")+"  发帖人:"+map.get("userName");
            		 mhMessage = "{\"articles\" : [{" +
                             "\"title\" : \"新发表的帖子等待您的审核，请尽快完成\"," +
                             "\"pcurl\":\""  + pcurl  + "\","+
                             "\"description\" : \"" + title + "\"," +
                             "\"appUrl\" : \""  + messageUrl + "\"" +
                             "}]}";
            }else if (StringUtils.equals("3", map.get("checkStatus"))){
            	title = "帖子标题:"+ map.get("title")+"   驳回理由:"+map.get("rejection");
                mhMessage = "{\"articles\" : [{" +
                        "\"title\" : \"您发表的帖子审核未通过\"," +
                        "\"pcurl\":\""  + pcurl  + "\","+
                        "\"description\" : \"" + title + "\"," +
                        "\"appUrl\" : \""  + messageUrl + "\"" +
                        "}]}";
            }
	            Map<String, Object> mhMessageContent = new HashMap<String, Object>();
	            msgTypeMap.put("COCALL", "news");
	            mhMessageContent.put("news", JsonUtils.readValue(mhMessage));
	            messageMap.put("COCALL", mhMessageContent);
        }
        
        //weLink
        if (map.get("sendPath").indexOf("weLink") >= 0) {
        	String weLinkUrl = GlobalConstant.getConfig("app.mobile.wlk.front.url");
        	 //weLink信息
            String mhMessage = "";
            //审核中推送 门户 checkStatus：1
       	 	//审核不通过推送 门户 checkStatus：3
            String title = "";
            if (StringUtils.equals("1", map.get("checkStatus"))) {
            	title = "帖子标题:"+ map.get("title")+"  发帖人:"+map.get("userName");
            		 mhMessage = "{\"articles\" : [{" +
                             "\"title\" : \"新发表的帖子等待您的审核，请尽快完成\"," +
                             "\"pcurl\":\""  + pcurl  + "\","+
                             "\"description\" : \"" + title + "\"," +
                             "\"appUrl\" : \""  + messageUrl + "\"" +
                             "}]}";
            }else if (StringUtils.equals("3", map.get("checkStatus"))){
            	title = "帖子标题:"+ map.get("title")+"   驳回理由:"+map.get("rejection");
                mhMessage = "{\"articles\" : [{" +
                        "\"title\" : \"您发表的帖子审核未通过\"," +
                        "\"pcurl\":\""  + pcurl  + "\","+
                        "\"description\" : \"" + title + "\"," +
                        "\"appUrl\" : \""  + messageUrl + "\"" +
                        "}]}";
            }
            Map<String, Object> mhMessageContent = new HashMap<String, Object>();
            msgTypeMap.put("WLK", "news");
            mhMessageContent.put("news", JsonUtils.readValue(mhMessage));
            messageMap.put("WLK", mhMessageContent);
        }
        
        //发送
        if(!messageMap.isEmpty()) {
        	mobileMessageService.sendMobileMsg(baseCorpId,MODULE,userId,deptId,msgTypeMap,messageMap,request);
        }
        
      /*//邮件
        if (StringUtils.equals("1", map.get("isJob"))) {
	        Map<String, String> params = new HashMap<>();
	        if (map.get("remindStyle").indexOf("mail") >= 0) {
	        	params.put("recipienters", "{\"u\":\"" + userId + "\"}");// 收件人 u-用户，s-岗位，o-组织，g-群组
	        	params.put("sender", map.get("userId"));
	        	params.put("content", map.get("startTime")+" 论坛：项目汇报，请及时查看！");
	        	params.put("theme", map.get("title"));
	        	params.put("corpId", baseCorpId);
	        	RestClient restClient = new RestClient(false);
	            restClient.get("/mail/modelSendMail", map.get("token"), params);
	        }
        }*/

    }


    public static String convertContextPath(String serverUrl){
        String context = "";
        if(!"".equals(serverUrl)) {
        	serverUrl = serverUrl.substring(serverUrl.lastIndexOf("//")+2,serverUrl.length());
            int index = serverUrl.lastIndexOf("/");
            if(index>0){
                if(index == serverUrl.length()-1){// /在结尾
                    context="";
                }else{
                    context = serverUrl.substring(serverUrl.lastIndexOf("/")+1);
                }
            }else{
                context="";
            }
        }
        return context;
    }



    /**
     *
     * @param paramMap <br>
     *            String dataId, 推送信息id <br/>
     *            String msgType, 消息类型(非必填)，值范围：1-通知（提醒），2-待办，3-待阅，默认：1 <br/>
     *            String msgTitle, 消息标题 <br/>
     *            String msgContent, 消息内容 <br/>
     *            String openMode, 消息打开方式(非必填)， 不为空则跳转页面，否则跳转模态框 <br/>
     *            String url, 跳转路径 <br/>
     *            String calendarId,论坛id <br/>
     *            String msgReceiver, 消息接收对象，用户id，用逗号分隔<br/>
     *            String userId, 发送者用户id <br/>
     *            String corpId, 单位id <br/>
     *            String token  TOKEN <br/>
     *
     *            String start  开始时间<br>
     *            String end    结束时间<br>
     *            String repeat 是否是重复<br>
     */
    public static void sendMsgToOffice(Map<String, String> paramMap) throws Exception {
        Map<String, String> sendMap = new HashMap<>();
        sendMap.put("moduleCode", "forum");
        sendMap.put("moduleId", MODULEID);
        if (StringUtils.isNotBlank(paramMap.get("msgType"))) {
            sendMap.put("msgType", paramMap.get("msgType"));
        } else {
            sendMap.put("msgType", "1");
        }
        sendMap.put("dataId", paramMap.get("dataId"));
        sendMap.put("msgFmt", "1");
        sendMap.put("msgLevel", "3");
        sendMap.put("msgSenderType", "10");
        // 消息推送发送者
        sendMap.put("msgSender", paramMap.get("userId"));
        sendMap.put("corpId", paramMap.get("corpId"));
        sendMap.put("msgTitle", paramMap.get("msgTitle"));
        sendMap.put("msgContent", paramMap.get("msgContent"));
        sendMap.put("msgLink", paramMap.get("url"));
        String paramString = "{\"size\":\"fullscreen\",\"postId\":\"" + paramMap.get("id") + "\",\"checkStatus\":\"" + paramMap.get("checkStatus")+"\"}";
        sendMap.put("paramString", paramString);
        String msgReceiver = paramMap.get("msgReceiver");
        String[] recArr = msgReceiver.split(",");
        String msgReceiverStr = "";
        for (String rec : recArr) {
            msgReceiverStr += "{\"10\":\"" + rec + "\"},";
        }
        if (StringUtils.isNotBlank(msgReceiverStr)) {
            msgReceiverStr = msgReceiverStr.substring(0, msgReceiverStr.length() - 1);
        }
        sendMap.put("msgReceiver", "[" + msgReceiverStr + "]");
        RestClient restClient = new RestClient(true);
        ObjectMapper mapper = new ObjectMapper();
        try {
            String msg = restClient.post("/system/umc/message/sendmessage", paramMap.get("token"),
                    new HashMap<String, String>(), mapper.writeValueAsString(sendMap));
        } catch (JsonProcessingException e) {
        }
    }
    
    /**
	    * 刪除消息
	    * @param applyRecordId
	    * @param corpId
	    * @param token
	    */
	  public static void deleteMessage(List<String> dataIds, String corpId, String token) {
	    try {
	      if(CollectionUtils.isNotEmpty(dataIds)) {
	        for(String dataId : dataIds) {
	          Map<String, String> params = new HashMap<String, String>();
	          params.put("corpId", corpId);
	          params.put("dataId", dataId);
	          params.put("moduleCode", "forum");
	          RestClient restClient = new RestClient(true);
	          restClient.post("/system/umc/message/deleteMessages", token , params);
	        }
	      }
	    } catch (Exception e) {
	      e.printStackTrace();
	    }
	  }
	  
	  /**
	    * 已读同步消息(异步请求)
	    * @param msgType
	    * @param corpId
	    * @param token
	    */
	  @Async
	  public static void takeMsgDone(ForumPost forumPost, String corpId, String token,String userId) {
	    try {
	    	Map<String,String> map = new HashMap<>();
	    	RestClient restClient = new RestClient(true);
	    	String ids = "[{\"10\":\""+userId+"\"}";
			map.put("msgType", "1");
			map.put("moduleCode", "forum");
			map.put("corpId", corpId);
			map.put("dataId", forumPost.getId());
			map.put("receiver", ids+"]");
			restClient.post("/system/umc/message/takeMsgDone", token, map);
	    } catch (Exception e) {
	      e.printStackTrace();
	    }
	  }
	  
	  /**
	     *
	     * @param paramMap <br>
	     *            String dataId, 推送信息id <br/>
	     *            String msgType, 消息类型(非必填)，值范围：1-通知（提醒），2-待办，3-待阅，默认：1 <br/>
	     *            String msgTitle, 消息标题 <br/>
	     *            String msgContent, 消息内容 <br/>
	     *            String openMode, 消息打开方式(非必填)， 不为空则跳转页面，否则跳转模态框 <br/>
	     *            String url, 跳转路径 <br/>
	     *            String calendarId,日程id <br/>
	     *            String msgReceiver, 消息接收对象，用户id，用逗号分隔<br/>
	     *            String userId, 发送者用户id <br/>
	     *            String corpId, 单位id <br/>
	     *            String token  TOKEN <br/>
	     *
	     *            String start  开始时间<br>
	     *            String end    结束时间<br>
	     *            String repeat 是否是重复<br>
	     * @param userMapList 
	     */
	    @Async 
	    public static void sendSms(Map<String, String> paramMap, List<Map<String, Object>> userMapList) throws Exception {
	    	if(StringUtils.equals(paramMap.get("smsPath"), "1")) {
	    		RestClient restClient = new RestClient(true);
	    		Map<String, String> mapSms = new HashMap<String, String>();
	    		mapSms.put("paramStr", JsonUtils.writeValueAsString(paramMap));
	    		String msg = restClient.post("/sms/savePendingSms", paramMap.get("token"), mapSms);
	    	}
	    }
}
